package com.apestech.framework.web.lib;

import com.apestech.framework.file.BufferFileRead;
import com.apestech.framework.file.callback.ReadBufferFileCallBackHandler;
import com.apestech.framework.json.JSON;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.util.StringUtil;

import java.io.*;

/**
 * @author hup
 * @create 2018-10-26-9:33
 */
public class BufferJSONWrite {

    private int fetchSize=100;
    private int index=0;
    private BufferOS os;
    private String charset="UTF-8";
    private String wcharset="GBK";
    private String tempfile;

    public BufferJSONWrite() throws Exception {
        this.tempfile= LocalVariable.getTempDir()+ StringUtil.getUUID()+".txt";
        FileUtil.createDir(this.tempfile);
        this.os=new BufferOS(new FileOutputStream(tempfile));
    }

    public void setFetchSize(int fetchSize) {
        this.fetchSize = fetchSize;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public void setWcharset(String wcharset) {
        this.wcharset = wcharset;
    }

    public void writeDetailData(WriteBody writeBody) throws Exception{
        if(index % fetchSize==0){
            os.flush();
        }
        String s=writeBody.write();
        if(index>0 && s!=null && !"".equals(s.trim())){
            os.write(",".getBytes(charset));
        }
        os.write(s.getBytes(charset));
        index++;
    }

    public void getDetailData(ReadBufferFileCallBackHandler readBufferFileCallBackHandler) throws Exception{
        os.flush();
        os.close();
        BufferFileRead read=new BufferFileRead(tempfile);
        read.setOnlytext(false);
        read.getFileText(readBufferFileCallBackHandler, 0);
        read.close();
    }

    public void close() throws Exception {
        os.close();
        FileUtil.deleteFile(tempfile);
    }

}
